#!/usr/bin/python
'''
dlm2dot.py
	
usage:
	randomClusters.py input_file k > output_file
		input: input file name and the number of clusters to use k.
		output: the cluster file

Created on May 2, 2011
@author: ncrowell
'''

import sys
import random

# Produces the set containings all of the nodes in the input
def processInput(f):
	ret = set()
	for line in f.readlines():
		if (line.strip().startswith('#')):
			continue
		s = line.split()
		if ( len(s) > 0 ):
			s = line.split()
			u = s[0]
			v = s[1]
			ret.add(u)
			ret.add(v)

	return list(ret)

# Produce equally sized random clusters
def genClusters(nodes, k, f):
	# permute the nodelist 
	N = len(nodes)
	for i in range(N):
		j = random.randint(0,N-1)
		nodes[i], nodes[j] = nodes[j], nodes[i]

	# number of nodes per cluster
	n = N / k
	rem = N % k
	for i in range(k):
		f.write(str(i) + ":")
		for j in range(n):
			v = nodes[ i*n + j ]
			f.write(" " + v)
		if ( i < rem ): # just distribute the remainder over the earlier clusters
			v = nodes[ k*n +  i]
			f.write(" " + v)
		f.write("\n")

def main():
	if ( len(sys.argv) != 3 ): 
		print ("usage:\n" +
			"\trandomClusters.py input_file k > output_file\n" +
			"\t\tinput: input file name and the number of clusters to use k\n" +
			"\t\toutput: the cluster file\n")
		sys.exit()	

	inputfile = file(sys.argv[1], 'r')
	k = int(sys.argv[2])	
	outputfile = sys.stdout

	# process edge list
	nodelist = processInput(inputfile)

	inputfile.close()


	# genereate dot file from graph list
	genClusters(nodelist, k, outputfile)



if __name__ == '__main__':
	main()
